package com.matrix.dungeon;

import com.matrix.dungeon.Generate.Node;

public class Heap {
	Node[] data;
	int numOfItem = 0;
	
	public Heap(int pSize){
		data = new Node[pSize + 1];
	}
	
	public void add(Node pCell){
		numOfItem++;
		data[numOfItem] = pCell;
		
		int index = numOfItem;
		while(true){
			if(index == 1)break;
			
			if(data[index].value <= data[index/2].value){
				Node tmp = data[index];
				data[index] = data[index/2];
				data[index/2] = tmp;
				index /=2;
			}else{
				break;
			}
		}
	}
	
	public void del(){
		data[1] = data[numOfItem];
		data[numOfItem] = null;
		numOfItem--;
		
		int index = 1;
		while(true){
			if(index * 2 >= numOfItem)break;
			
			if(data[index].value > data[index * 2].value && data[index * 2].value <= data[index * 2 + 1].value){
				Node tmp = data[index];
				data[index] = data[index * 2];
				data[index * 2] = tmp;
				index *= 2;
			}else if(data[index].value > data[index * 2 + 1].value && data[index * 2 + 1].value < data[index * 2].value){
				Node tmp = data[index];
				data[index] = data[index * 2 + 1];
				data[index * 2 + 1] = tmp;
				index = index * 2 + 1;
			}else{
				break;
			}
		}
	}
	
	public void setItem(int pX, int pY, Node pCell){
		int index = isContain(pX, pY);
		if(index != -1){
			data[index] = pCell;
			while(true){
				if(index == 1)break;
				
				if(data[index].value < data[index/2].value){
					Node tmp = data[index];
					data[index] = data[index/2];
					data[index/2] = tmp;
					index /=2;
				}else{
					break;
				}
			}
		}
	}
	
	public int isContain(int pX, int pY){
		for(int i = 1;i <= numOfItem;i++){
			if(data[i].x == pX && data[i].y == pY){
				return i;
			}
		}
		return -1;
	}
	
	public boolean isEmpty(){
		return numOfItem == 0;
	}
	
	public Node getTop(){
		return data[1];
	}
}
